const express = require('express');
const {loginService, updateAdminService} = require("../service/adminService");
const {formatResponse, analyseToken} = require("../utils/tool");
const {ValidationError} = require("../utils/errors");
const router = express.Router();

// 登录
router.post('/login', async function (req, res, next) {
    // console.log(req.body);
    if (req.body.captcha.toLowerCase() !== req.session.captcha.toLowerCase()) {
        throw new ValidationError('验证码错误')
    }
    // 验证码验证
    const result = await loginService(req.body);
    if (result.token) {
        res.setHeader('authentication', result.token);
    }
    res.send(formatResponse(0, '', result.data));
});

// 恢复登录状态
router.get('/whoami', async function (req, res, next) {
    // 获取并解析 token
    const data = analyseToken(req.get('Authorization'))
    res.send(formatResponse(0, '', {
        loginId: data.loginId,
        name: data.name,
        id: data.id
    }));
})

// 更新用户信息
router.put('/', async function (req, res, next) {
    res.send(await updateAdminService(req.body));
})

module.exports = router;
